import React, { Suspense } from 'react'
import { Canvas } from '@react-three/fiber'
import { useModelStore } from '@/stores'
import { useModelFile } from '@/hooks/useModelFile'
import { Scene } from './Scene'
import { Model } from './Model'
import { EmptyState } from './EmptyState'

export default function ThreeDSimulator() {
  // 分别订阅，避免返回新对象导致不必要的重渲染
  const models = useModelStore((state) => state.models)
  const isLoading = useModelStore((state) => state.isLoading)
  const error = useModelStore((state) => state.error)

  // 监听窗口加载文件
  useModelFile()

  return (
    <div style={{ width: '100%', height: '100%', position: 'relative' }}>
      {models.length === 0 && !isLoading && <EmptyState />}
      
      {error && (
        <div
          style={{
            position: 'absolute',
            top: '50%',
            left: '50%',
            transform: 'translate(-50%, -50%)',
            color: '#ff4d4f',
            textAlign: 'center',
            zIndex: 10,
            padding: '20px',
            backgroundColor: 'rgba(255, 255, 255, 0.9)',
            borderRadius: '4px',
          }}
        >
          <p>加载错误: {error}</p>
        </div>
      )}

      <Suspense
        fallback={
          <div style={{ color: '#fff', padding: '20px', textAlign: 'center' }}>
            {isLoading ? '加载模型中...' : '准备就绪'}
          </div>
        }
      >
        <Canvas
          camera={{ position: [0, 0, 5], fov: 75 }}
          gl={{
            antialias: true,
            preserveDrawingBuffer: false,
          }}
          dpr={[1, window.devicePixelRatio || 2]}
          style={{ width: '100%', height: '100%', display: 'block' }}
        >
          <Scene />
          {/* 渲染所有模型，每个模型都有独立的 useGLTF 实例和位置偏移 */}
          {models.map((model, index) => {
            console.log('🚀 ~ 渲染模型:', model.id, model.name, model.modelPath, 'index:', index)
            return <Model key={model.id} modelPath={model.modelPath} index={index} />
          })}
        </Canvas>
      </Suspense>
    </div>
  )
}
